﻿using System;
using Newtonsoft.Json.Linq;

namespace SilverTwitterSearch
{
    /// <summary>
    /// Describes a Tweet.
    /// </summary>
    public struct Tweet
    {
        #region Properties
        /// <summary>
        /// Gets or sets the creation datetime.
        /// </summary>
        public DateTime CreatedAt 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets the name of the author.
        /// </summary>
        public string FromUser 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets the ID of the author.
        /// </summary>
        public long FromUserId 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets the Tweet ID.
        /// </summary>
        public long Id 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets the URL to the authors profile image.
        /// </summary>
        public string ProfileImage 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets the Sourcestring (Client-name and URL).
        /// </summary>
        public string Source 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets or sets the text
        /// </summary>
        public string Text 
        { 
            get; 
            set; 
        }

        /// <summary>
        /// Gets the ID of a mentioned user if the tweet contains a mention.
        /// </summary>
        public long? ToUserId 
        { 
            get; 
            set; 
        }
        #endregion

        #region Read From JSON
        /// <summary>
        /// Creates a new <see cref="Tweet"/>-instance from the given JSON-Token.
        /// </summary>
        /// <param name="token">JSON-Token containing the Tweet-data</param>
        /// <returns>Object holding the data provided in the JSON-token</returns>
        public static Tweet ReadFromJson(JToken token)
        {
            return new Tweet()
            {
                CreatedAt = DateTime.Parse(token["created_at"].ToString()),
                FromUser = token["from_user"].ToString(),
                FromUserId = long.Parse(token["from_user_id"].ToString()),
                Id = long.Parse(token["id"].ToString()),
                ProfileImage = token["profile_image_url"].ToString(),
                Source = token["source"].ToString(),
                Text = token["text"].ToString(),
                ToUserId = !String.IsNullOrEmpty(token["to_user_id"].ToString()) 
                ? long.Parse(token["to_user_id"].ToString()) 
                : new long?()
            };
        }
        #endregion
    }
}